package com.qipay.admin;

import com.qipay.admin.utils.ExportUtil;
import com.qipay.baas.model.Peizhi;
import com.qipay.notice.NoticeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by back on 2016/9/15.
 */
@Controller
public class BaseController  {
    @Value("${web.static.url.host}")
    protected String StaticHost;

    @Value("${web.static.version}")
    protected String StaticVersion;

    @Autowired
    NoticeService noticeService;

    protected static org.apache.poi.ss.usermodel.Cell cell = null;
    protected static Row row=null;
    protected static HSSFCellStyle style; //设置表头的类型
    protected static HSSFCellStyle style1;// 设置数据类型
    protected static HSSFFont font;//设置字体
    protected static HSSFHeader header;// 设置sheet的头
    protected static HSSFWorkbook workbook;// 一个excel
    protected static HSSFSheet exportSheet;


    protected ModelAndView createModelAndView(String name){
        ModelAndView modelAndView = new ModelAndView(name);
        modelAndView.addObject("StaticHost", StaticHost);
        modelAndView.addObject("StaticVersion", StaticVersion);
        modelAndView.addObject("peizhi",findPeizhi());
        return modelAndView;
    }

    public Peizhi findPeizhi(){
        Peizhi peizhi = noticeService.getPeizhi();
        return peizhi;
    }

    public String  getParamStr(Map<String , Object> paramMap){
        SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap);
        StringBuffer stringBuffer = new StringBuffer();
        for (Map.Entry<String, Object> m : smap.entrySet()) {
            Object value = m.getValue();
            if (value != null && StringUtils.isNotBlank(String.valueOf(value))){
                stringBuffer.append(m.getKey()).append("=").append(value).append("&");
            }
        }
        stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
        return stringBuffer.toString();
    }

    public String generateAutoSubmitHtml(Map<String, Object> paramMap,String actionUrl) {

        StringBuilder html = new StringBuilder();
        html.append("<html><head></head><body>").append("<form id='pay_form' name='pay_form' action='")
                .append(actionUrl).append("' method='POST'>\n");

        for (String key : paramMap.keySet()) {
            String value = paramMap.get(key).toString();
            //银联快捷，输入验证码输入框的不隐藏
            if("verifyCode".equals(key))html.append("<input type='text' name='" + key + "' value='" + value + "'>\n");
            if( value!= null && !value.isEmpty()){
                html.append("<input type='hidden' name='" + key + "' value='" + value + "'>\n");

            }
        }

        html.append("</form>\n")
                .append("<script language='javascript'>window.onload=function(){document.pay_form.submit();}</script>\n")
                .append("</body></html>");

        return html.toString();
    }

    protected static void initParam(String title){
        exportSheet = workbook.createSheet(title); //创建一个sheet
    }

    /**
     * 导出第一步，初始化excel表
     */
    protected static void initExcel(){
        workbook = new HSSFWorkbook(); // 创建一个excel
        style = workbook.createCellStyle(); // 设置表头的类型
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style1 = workbook.createCellStyle(); // 设置数据类型
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        font = workbook.createFont(); // 设置字体
    }
    /**
     * 导出第一步，写入导出数据的
     * objects导出的对象集合
     * 表头的名称数组，表名称
     * 有几个sheet，就调用几次
     */
    protected static void daochu (List<?> objects, String[]tableHeader){
        short cellNumber = (short) tableHeader.length;// 表的列数
        header = exportSheet.getHeader();// 设置sheet的头
        try {
            if (objects==null||objects.size() < 1) {
                ////System.out.println(111);
                header.setCenter("无相关数据信息");
            } else {
                ////System.out.println(2222);
                row = exportSheet.createRow(0);
                row.setHeight((short) 400);
                for (int k = 0; k < cellNumber; k++) {
                    cell = row.createCell(k);// 创建第0行第k列
                    //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                    cell.setCellValue(tableHeader[k]);// 设置第0行第k列的值
                    short y = (short) 6000;
                    exportSheet.setColumnWidth(k, y);// 设置列的宽度
                    font.setColor(HSSFFont.COLOR_NORMAL); // 设置单元格字体的颜色.
                    font.setFontHeight((short) 250); // 设置单元字体高度
                    style1.setFont(font);// 设置字体风格
                    cell.setCellStyle(style1);
                }
                // 开始循环写入
                for (int i = 0; i < objects.size(); i++) {
                    Object o =objects.get(i);// 获取student对象
                    Field[] fileds = o.getClass().getDeclaredFields();
                    List<Object>values = new ArrayList<Object>();
                    for (Field f:fileds) {
                        f.setAccessible(true);//抑制对私有属性的检查
                        if(f.getName().indexOf("ls")!=0&&!"userId".equals(f.getName())){
                            values.add(f.get(o));
                        }
                    }
                    row = exportSheet.createRow((short) (i + 1));// 创建第i+1行
                    row.setHeight((short) 400);// 设置行高

                    for(int l=0;l<values.size();l++){
                        cell = row.createCell(l); // 创建第i+1行第l列
                        cell.setCellValue(values.get(l)==null?"":values.get(l).toString());// 设置第i+1行第l列的值
                        cell.setCellStyle(style); // 设置风格
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出第三步，io写出，保存excel表
     * title:保存的excel名
     */
    protected static void finishExcel(String title,HttpServletResponse response){
        OutputStream out = null;// 创建一个输出流对象
        try {
            out = response.getOutputStream();//

            String headerStr = title;
            headerStr = new String(headerStr.getBytes("utf-8"), "ISO8859-1");// headerString为中文时转码
            response.setHeader("Content-disposition", "attachment; filename="
                    + headerStr + ".xls");// filename是下载的xls的名，建议最好用英文
            response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
            response.setHeader("Pragma", "No-cache");// 设置头
            response.setHeader("Cache-Control", "no-cache");// 设置头
            response.setDateHeader("Expires", 0);// 设置日期头
            workbook.write(out);
            out.flush();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
